﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Xml.Linq;
using System.Diagnostics;
using System.IO;

namespace SmartText
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int MAX_TEXT_NUMBER = 20000;
        private LuaTextTemplate.LuaTextTemplate _ltt = new LuaTextTemplate.LuaTextTemplate();
        private AppInfo _info;

        public MainWindow()
        {

            InitializeComponent();

            Properties.Settings.Default.Upgrade();  // enable to load settings from previous version
            Properties.Settings.Default.Reload();
            App.LoadLanguage(Properties.Settings.Default.Lang);

            _info = ((App)Application.Current).Info;
            this.grid.DataContext = _info;

            if (!_info.HasCommandLineArgs)
            {
                _info.Template = Properties.Settings.Default.Template;
                _info.Param = Properties.Settings.Default.Param;
                _info.Output = Properties.Settings.Default.Output;

                _info.TemplateEncoding = Encoding.GetEncoding(Properties.Settings.Default.TemplateEncoding);
                _info.ParamEncoding = Encoding.GetEncoding(Properties.Settings.Default.ParamEncoding);
                _info.OutputEncoding = Encoding.GetEncoding(Properties.Settings.Default.OutputEncoding);
                _info.LangInfo = (from li in ((App)Application.Current).LanguageList
                                  where li.Lang == Properties.Settings.Default.Lang
                                  select li).First();
                Rect bounds = Properties.Settings.Default.WindowPosition;
                if (!bounds.IsEmpty)
                {
                    this.Top = bounds.Top;
                    this.Left = bounds.Left;
                    this.Width = bounds.Width;
                    this.Height = bounds.Height;
                }
            }
        }

        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            if (CheckInput())
            {
                Generate();
            }
        }

        private void Generate()
        {
            string sResult = null;
            string sParam = null;
            var sw = new Stopwatch();
            bool bSetParam;

            try
            {
                sw.Start();
                _ltt.SetTemplate(File.ReadAllText(_info.Template, _info.TemplateEncoding));
                sParam = GetParam();
                bSetParam = _ltt.SetLuaParam(sParam);
                if (bSetParam)
                {
                    sResult = _ltt.Generate();
                }
                if (!bSetParam || sResult == null)
                {
                    txtOutputText.Foreground = new SolidColorBrush(Colors.Red);
                    if (!bSetParam || string.IsNullOrWhiteSpace(sParam))
                    {
                        _info.OutputText = _ltt.ErrorMessage;
                    }
                    else
                    {
                        _info.OutputText = _ltt.ErrorMessage + "\r\n\r\nParameter:\r\n" + sParam;
                    }
                    _info.OutputSuccess = false;
                    MessageBox.Show(App.GetLanguageText("generate_ng"), this.Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
                else
                {
                    txtOutputText.Foreground = new SolidColorBrush(Colors.Black);
                    if (sResult.Length > MAX_TEXT_NUMBER && _info.Output != string.Empty)
                    {
                        _info.OutputText = sResult.Substring(0, MAX_TEXT_NUMBER) + "\r\n" + App.GetLanguageText("see_output_file");
                    }
                    else
                    {
                        _info.OutputText = sResult;
                    }

                    if (!string.IsNullOrEmpty(_info.Output))
                    {
                        File.WriteAllText(_info.Output, sResult, _info.OutputEncoding);
                    }
                    _info.OutputSuccess = true;
                    if (!_info.HasCommandLineArgs)
                    {
                        MessageBox.Show(App.GetLanguageText("generate_ok") + sw.Elapsed.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
            }
            catch (System.Exception e)
            {
                txtOutputText.Foreground = new SolidColorBrush(Colors.Red);
                _info.OutputText = e.Message + "\r\n" + e.StackTrace;
                _info.OutputSuccess = false;
                MessageBox.Show(App.GetLanguageText("generate_ng"), this.Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private bool CheckInput()
        {
            return fileBindingGroup.CommitEdit();
        }

        private void grid_Error(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
            {
                _info.OutputSuccess = false;
                MessageBox.Show(e.Error.ErrorContent.ToString(), this.Title, MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }
        }

        private string GetParam()
        {
            string sParam = string.Empty;

            switch (System.IO.Path.GetExtension(_info.Param).ToUpper())
            {
                case ".CSV":
                    sParam = Converter.CSVToLua.ConvertToLua(_info.Param, _info.ParamEncoding);
                    break;
                case ".XML":
                    sParam = Converter.XMLToLua.ConvertToLua(_info.Param, _info.ParamEncoding);
                    break;
                case ".LUA":
                    sParam = File.ReadAllText(_info.Param, _info.ParamEncoding);
                    break;
            }

            return sParam;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!_info.HasCommandLineArgs)
            {
                Properties.Settings.Default.Param = _info.Param;
                Properties.Settings.Default.Template = _info.Template;
                Properties.Settings.Default.Output = _info.Output;
                Properties.Settings.Default.WindowPosition = this.RestoreBounds;
                Properties.Settings.Default.TemplateEncoding = _info.TemplateEncoding.CodePage;
                Properties.Settings.Default.ParamEncoding = _info.ParamEncoding.CodePage;
                Properties.Settings.Default.OutputEncoding = _info.OutputEncoding.CodePage;
                Properties.Settings.Default.Lang = _info.LangInfo.Lang;
                Properties.Settings.Default.Save();
            }
        }

        private void btnOption_Click(object sender, RoutedEventArgs e)
        {
            var settingWindow = new OptionWindow(_info);
            settingWindow.ShowDialog();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (_info.HasCommandLineArgs)
            {
                btnGenerate_Click(null, null);
                if (_info.OutputSuccess)
                {
                    this.Close();
                }
            }
        }

        private void btnAbout_Click(object sender, RoutedEventArgs e)
        {
            new About().ShowDialog();
        }
    }
}
